package com.huatai.bpmn.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.bpmn.commom.util.SecurityUtil;
import com.huatai.bpmn.constant.MinioBucket;
import com.huatai.bpmn.constant.PMPConstant;
import com.huatai.bpmn.entity.*;
import com.huatai.bpmn.entity.dto.CompletionDto;
import com.huatai.bpmn.entity.dto.PageDto;
import com.huatai.bpmn.entity.vo.*;
import com.huatai.bpmn.service.*;
import com.huatai.bpmn.utils.Activiti7Util;
import com.huatai.common.api.R;
import com.huatai.common.config.MinioAPI;
import com.huatai.common.entity.UserInfo;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.AuthUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import com.huatai.user.dubbo.UserDubboApi;
import com.huatai.user.entity.User;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @author :yxy
 * @date : 2024/2/22
 */
@Service
public class YYActivitiServiceImpl implements YYActivitiService {
	@Value("${history.consent}")
	private String consent;
	@Value("${history.notConsent}")
	private String notConsent;
	@Value("${history.consentColor}")
	private String consentColor;
	@Value("${history.notConsentColor}")
	private String notConsentColor;
	@Value("${history.reload}")
	private String reload;

	@Autowired
	private MinioAPI minioAPI;
	@Autowired
	private DeployFormMappingService deployFormMappingService;
	@Autowired
	private YYExternalParameterService yyExternalParameterService;
	@Autowired
	private BasicLoadService basicLoadService;
	@Autowired
	private YYDataInfoService yyDataInfoService;
	@Autowired
	private BasicDataService basicDataService;
	@DubboReference(timeout = 30000, check = false, retries = 0)
	private UserDubboApi userDubboApi;
	@Autowired
	private TbCompleteTaskStatusService completeTaskStatusService;
	@Autowired
	private InvestCapitalService investCapitalService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UrgeCheckService urgeCheckService;
	@Autowired
	private UserGroupService userGroupService;

	/**
	 * 流程部署
	 *
	 * @param file
	 * @param deployName
	 * @param externalParameterId
	 * @return
	 * @throws IOException
	 */
	@Override
	public R<Map<String, Object>> deploy(MultipartFile file, String deployName, String externalParameterId, int type) {
		//读书文件流
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}

		//创建processEngine
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		//得到repositoryService实例
		RepositoryService repositoryService = processEngine.getRepositoryService();
		//使用repositoryService进行部署
		Deployment deployment = repositoryService.createDeployment().addInputStream(file.getOriginalFilename(), inputStream).name(deployName).deploy();
		String myKey = findProcdefKey(deployment.getId());
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);
		if (ObjectUtil.isEmpty(deployFormMappingEntity)) {
			//将部署的id和表单进行绑定
			deployFormMappingEntity = new DeployFormMappingEntity();
		}
		deployFormMappingEntity.setDeploymentid(deployment.getId());
		deployFormMappingEntity.setExternalParameterId(externalParameterId);
		deployFormMappingEntity.setMyKey(myKey);
		deployFormMappingEntity.setType(type);
		deployFormMappingService.saveOrUpdate(deployFormMappingEntity);
		//部署信息
		Map<String, Object> map = new HashMap<>();
		map.put("deploymentId", deployment.getId());
		map.put("deploymentName", deployment.getName());
		return R.data(map);
	}

	/**
	 * 查看部署流程集合
	 */
	@Override
	public R<Map<String, Object>> getDeployList(PageDto pageDto) {
		RepositoryService repositoryService = Activiti7Util.repositoryService;
		ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
		List<ProcessDefinition> list = new ArrayList<>();
		if (pageDto.getPage() == 0 || pageDto.getLimit() == 0) {
			list = processDefinitionQuery.latestVersion().list();
		} else {
			list = processDefinitionQuery.latestVersion().listPage((pageDto.getPage() - 1) * pageDto.getLimit(), pageDto.getLimit());
		}
		long total = processDefinitionQuery.latestVersion().count();
		List<DeploymentVO> deploymentVOList = new ArrayList<>();

		List<DeployFormMappingEntity> formMapping;
		if (pageDto.getType() == null) {
			formMapping = deployFormMappingService.list();
		} else {
			formMapping = deployFormMappingService.list(Wrappers.<DeployFormMappingEntity>lambdaQuery().eq(DeployFormMappingEntity::getType, pageDto.getType()));
		}

		List<YYExternalParameterEntity> configFormList = yyExternalParameterService.list();
		for (ProcessDefinition processDefinition : list) {
			Deployment deployment = findDeploymentInfo(processDefinition.getDeploymentId());
			DeploymentVO deploymentVO = new DeploymentVO();
			deploymentVO.setDeployId(deployment.getId());
			deploymentVO.setDeployName(deployment.getName());
			deploymentVO.setCreateTime(deployment.getDeploymentTime());
			deploymentVO.setDefinitionKey(findProcdefKey(deployment.getId()));
			for (DeployFormMappingEntity deployFormMappingEntity : formMapping) {
				if (deployFormMappingEntity.getDeploymentid().equals(deployment.getId())) {
					deploymentVO.setPlace(deployFormMappingEntity.getExternalParameterId());
//					deploymentVO.setCompleteFormKey(deployFormMappingEntity.getCompleteId());
					deploymentVOList.add(deploymentVO);
					break;
				}
			}
//			deploymentVO.setPlace(findExternalParameterId(deployment.getId()));
		}
		for (DeploymentVO deploymentVO : deploymentVOList) {
			if (deploymentVO.getPlace() == null) {
				continue;
			}
			for (YYExternalParameterEntity externalParameterEntity : configFormList) {
				if (deploymentVO.getPlace().equals(externalParameterEntity.getId())) {
					deploymentVO.setFormName(externalParameterEntity.getName());
				}
			}
		}
		Map<String, Object> map = new HashMap<>();
		UserInfo user = AuthUtil.getUser();
		/*if (PMPConstant.USER_POST_ZJL.equals(user.getPostId().toString()) || PMPConstant.DEPART_CWB_ID.equals(user.getDeptId().toString()) || PMPConstant.DEPART_SCB_ID.equals(user.getDeptId().toString()) || "admin".equals(user.getAccount())) {
			deploymentVOList.sort((t1, t2) -> t2.getCreateTime().compareTo(t1.getCreateTime()));
			//去掉黑名单
			deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_HMD)).collect(Collectors.toList());
			//去掉实施
			deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_SS)).collect(Collectors.toList());
			//去掉修改
			deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_UPD)).collect(Collectors.toList());
			//去掉人工天操作
			deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_SS_INFO)).collect(Collectors.toList());
		} else {
			//只保留商机创建项目
			deploymentVOList = deploymentVOList.stream().filter(x -> x.getDefinitionKey().equals(PMPConstant.TABLE_SJ)).collect(Collectors.toList());
		}*/
		//去掉入库
		deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_RK)).collect(Collectors.toList());
		//去掉黑名单
		deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_HMD)).collect(Collectors.toList());
		//去掉实施
		deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_SS)).collect(Collectors.toList());
		//去掉修改
		deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_UPD)).collect(Collectors.toList());
		//去掉入库实施
		deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_RK_SS_INFO)).collect(Collectors.toList());
		//去掉入库运维
		deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_RK_YW_INFO)).collect(Collectors.toList());
		//去掉商机提前投入
		deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_SJ_TQ_INFO)).collect(Collectors.toList());
		//只有刘萍萍可以发起商机
		if (!user.getUserId().toString().equals(PMPConstant.USER_ID_LPP)) {
			//去掉商机
			deploymentVOList = deploymentVOList.stream().filter(x -> !x.getDefinitionKey().equals(PMPConstant.TABLE_SJ)).collect(Collectors.toList());
		}
		map.put("deploymentList", deploymentVOList);
		map.put("total", Integer.parseInt(String.valueOf(total)));
		return R.data(map);
	}

	/**
	 * 创建流程定义-创建项目数据
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean startProcess(JSONObject jsonObject, String uuid) {
		String myKey = jsonObject.getString("definitionKey");
		UserInfo user = AuthUtil.getUser();
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);

		String externalParameterId = deployFormMappingEntity.getExternalParameterId();
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)) {
			throw new RuntimeException("项目表单配置参数不能为空");
		}
		//将业务数据进行存储
		//表单数据
		if (StringUtil.isEmpty(uuid)) {
			uuid = UUID.randomUUID().toString().replaceAll("-", "");
		}
		YYDataInfoEntity yyDataInfoEntity = yyDataInfoService.getBusinessKey(uuid);
		if (!ObjectUtil.isEmpty(yyDataInfoEntity)) {
			if (PMPConstant.STATUS_1.equals(yyDataInfoEntity.getStatus())) {
				throw new RuntimeException("当前数据正在操作中");
			}
		}

		String time = jsonObject.getJSONObject("param").getOrDefault("yjqysj", "").toString();
		//只有修改需要审核
		if (!(PMPConstant.TABLE_UPD.equals(myKey))) {
			basicLoadService.add(jsonObject.getJSONObject("param"), externalParameterEntity.getPlace(), uuid);
			//表格数据
			JSONObject data = jsonObject.getJSONObject("data");
			Set<String> keySet = data.keySet();
			for (String s : keySet) {
				JSONArray jsonArray = data.getJSONArray(s);
				for (int i = 0; i < jsonArray.size(); i++) {
					//针对前期投入需要根据不同权限控制
					basicLoadService.add(jsonArray.getJSONObject(i), s, uuid);
				}
			}
			DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			yyDataInfoEntity = new YYDataInfoEntity();
			yyDataInfoEntity.setFlowId(uuid);
			yyDataInfoEntity.setCreator(AuthUtil.getUser().getUserId());
			yyDataInfoEntity.setMyKey(myKey);
			yyDataInfoEntity.setStatus(PMPConstant.STATUS_0);
			if (StringUtil.isEmpty(time)) {
				yyDataInfoEntity.setCreateTime(LocalDateTime.now());
			} else {
				yyDataInfoEntity.setCreateTime(LocalDateTime.parse(time, df));
			}
			//存储数据信息关联表
			yyDataInfoService.save(yyDataInfoEntity);
		}


		//1.获得engine对象
		ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
		/*//2.获得RepositoryService
		RepositoryService repositoryService = engine.getRepositoryService();
		//3.根据部署id来获得流程定义
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
			.processDefinitionKey(myKey).singleResult();*/
		//4.获得RuntimeService
		RuntimeService runtimeService = engine.getRuntimeService();
		TaskService taskService = engine.getTaskService();
		//5.根据流程定义（类）生成流程实例（对象），借助RuntimeService
		//修改审批，其他暂时不用
		if (PMPConstant.TABLE_UPD.equals(myKey)) {
			//项目只能由项目经理发起
			String xmjl = basicLoadService.getPmpValueByBus("xmjl", uuid);
			if (!user.getRealName().equals(xmjl)&&!StringUtil.isEmpty(xmjl)) {
				throw new ServiceException("只有项目经理可以发起数据修改");
			}
			HashMap<String, Object> map = new HashMap<>();
			map.put("assignee0", user.getUserId());
			map.put("flag", "true");
			List<String> userGroup = userGroupService.getUserByMyKey(myKey);
			map.put("userGroup", userGroup);
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(myKey, uuid, map);
			Task task = taskService.createTaskQuery().processDefinitionKey(myKey).processInstanceId(processInstance.getId()).taskAssignee(user.getUserId().toString()).singleResult();
			if (task != null) {
				//任务执行完毕
				taskService.complete(task.getId());
			}
			if (PMPConstant.TABLE_UPD.equals(myKey)) {
				BasicDataEntity basicDataEntity = new BasicDataEntity();
				basicDataEntity.setMyKey(myKey);
				basicDataEntity.setProcessId(processInstance.getId());
				basicDataEntity.setCreator(user.getUserId());
				basicDataEntity.setFlowId(uuid);
				basicDataEntity.setParam(jsonObject.toString());
				basicDataEntity.setCreateTime(LocalDateTime.now());
				basicDataEntity.setStatus(PMPConstant.STATUS_1);
				basicDataService.save(basicDataEntity);
				//修改的需要改变状态
				if (PMPConstant.TABLE_UPD.equals(myKey)) {
					yyDataInfoEntity.setStatus(PMPConstant.STATUS_1);
					yyDataInfoService.updateById(yyDataInfoEntity);
				}
			}
		} else {
			runtimeService.startProcessInstanceByKey(myKey);
		}

		return true;
	}

	@Override
	public void fileDelete(String url) {
		try {
			minioAPI.deleteFile(MinioBucket.BPMN_FILES, url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Autowired
	private SecurityUtil securityUtil;

	/**
	 * 查询待办任务列表
	 *
	 * @param myKey
	 * @return
	 */
	@Override
	public List<YYTaskVo> findToDoTask(String myKey, String UserId) {


		try {
			securityUtil.logInAs(UserId + "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		//1.获得engine
		ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
		//2.获取TaskService
		TaskService taskService = engine.getTaskService();
		RuntimeService runtimeService = engine.getRuntimeService();
		RepositoryService repositoryService = engine.getRepositoryService();
		//3.任务查询
		//通过用户和候选人查询任务
		List<Task> tasks = taskService.createTaskQuery().processDefinitionKey(myKey)
			.taskCandidateOrAssigned(UserId).taskCandidateGroup(UserId).list();


		//4.遍历集合，获得任务信息
		ArrayList<YYTaskVo> list = new ArrayList<>();
		for (Task task : tasks) {
			YYTaskVo yyTaskVo = new YYTaskVo();
			ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
			String deploymentId = processInstance.getDeploymentId();
			Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
			BasicDataEntity basicDataEntity = basicDataService.findByMykeyAndFlowId(myKey, processInstance.getBusinessKey());
			User user = userDubboApi.getUser(basicDataEntity.getCreator());
			yyTaskVo.setDeployName(deployment.getName());
			yyTaskVo.setCreator(user.getRealName());
			yyTaskVo.setFlowId(processInstance.getBusinessKey());
			yyTaskVo.setTaskName(task.getName());
			yyTaskVo.setMyKey(myKey);
			yyTaskVo.setTaskId(task.getId());
			yyTaskVo.setProcessInstanceId(processInstance.getProcessInstanceId());
			list.add(yyTaskVo);
		}
		return list;
	}

	/**
	 * 完成任务
	 *
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean completionTask(CompletionDto completionDto) {
		UserInfo user = AuthUtil.getUser();
		securityUtil.logInAs(user.getUserId() + "");
		String flowId = completionDto.getFlowId();
		YYDataInfoEntity yyDataInfoEntity = yyDataInfoService.getBusinessKey(flowId);
		String myKey = completionDto.getMyKey();
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		TaskService taskService = processEngine.getTaskService();
		Task task = taskService.createTaskQuery().processDefinitionKey(myKey).processInstanceId(completionDto.getProcessInstanceId()).taskCandidateOrAssigned(user.getUserId().toString()).taskCandidateGroup(user.getUserId().toString()).singleResult();
		//实施人工天流程单独走
		switch (myKey) {
			case PMPConstant.TABLE_SJ_TQ_INFO:
				ssComplet(completionDto, user, flowId, myKey, taskService, task);
				break;
			case PMPConstant.TABLE_UPD:
				updateComplet(completionDto, user, flowId, yyDataInfoEntity, myKey, taskService, task);
				break;
			default:
				allComplet(completionDto, flowId, yyDataInfoEntity, myKey, taskService, task);
		}

		return true;
	}

	//数据修改的完成任务操作
	private void updateComplet(CompletionDto completionDto, UserInfo user, String flowId, YYDataInfoEntity yyDataInfoEntity, String myKey, TaskService taskService, Task task) {
		if (task != null) {
			HashMap<String, Object> map = new HashMap<>();
			map.put("flag", completionDto.getStatus());
			//添加审批建议
			TbCompleteTaskStatusEntity completeTaskStatus = new TbCompleteTaskStatusEntity();
			completeTaskStatus.setTaskId(task.getId());
			completeTaskStatus.setStatus(completionDto.getStatus());
			completeTaskStatus.setApprovalProposal(completionDto.getApprovalProposal());
			//添加到审批意见表中
			completeTaskStatusService.save(completeTaskStatus);
			if ("审核".equals(task.getName())) {
				//拾取任务
				taskService.claim(task.getId(), user.getUserId().toString());
				//当status为true时，需要修改数据状态为完成
				if ("true".equals(completionDto.getStatus())) {
					//数据修改，先删除原有数据再新增
					basicLoadService.removeByBusinessKey(flowId);
					dataAdd(flowId, myKey, yyDataInfoEntity.getMyKey());
					//修改状态
//					BasicDataEntity basicDataEntity = basicDataService.findByMykeyAndFlowId(myKey, flowId);
//					basicDataEntity.setStatus(PMPConstant.STATUS_0);
//					basicDataService.updateById(basicDataEntity);
				}
			}
			//完成任务
			taskService.complete(task.getId(), map);
		}
	}

	//没有特殊审批的任务完成任务的操作
	private void allComplet(CompletionDto completionDto, String flowId, YYDataInfoEntity yyDataInfoEntity, String myKey, TaskService taskService, Task task) {
		if (task != null) {
			if ("审核".equals(task.getName())) {
				HashMap<String, Object> map = new HashMap<>();
				map.put("flag", completionDto.getStatus());

				//当status为true时，商机新增的临时数据需要存储到正式数据
				if ("true".equals(completionDto.getStatus())) {
					if (PMPConstant.CHECK_ADD.equals(completionDto.getType())) {

						dataAdd(flowId, myKey, myKey);
					} else {
						//数据修改，先删除原有数据再新增
						basicLoadService.removeByBusinessKey(flowId);
						dataAdd(flowId, myKey, yyDataInfoEntity.getMyKey());
					}
				}
				taskService.complete(task.getId(), map);
			} else {
				taskService.complete(task.getId());
			}
		}
	}

	//实施人工天完成任务的操作
	private void ssComplet(CompletionDto completionDto, UserInfo user, String flowId, String myKey, TaskService taskService, Task task) {
		if (task != null) {
			HashMap<String, Object> map = new HashMap<>();
			map.put("flag", completionDto.getStatus());
			//添加审批建议
			TbCompleteTaskStatusEntity completeTaskStatus = new TbCompleteTaskStatusEntity();
			completeTaskStatus.setTaskId(task.getId());
			completeTaskStatus.setStatus(completionDto.getStatus());
			completeTaskStatus.setApprovalProposal(completionDto.getApprovalProposal());
			//添加到审批意见表中
			completeTaskStatusService.save(completeTaskStatus);
			if ("审批人".equals(task.getName())) {
				//拾取任务
				taskService.claim(task.getId(), user.getUserId().toString());
				//当status为true时，需要修改数据状态为完成
				if ("true".equals(completionDto.getStatus())) {
					BasicDataEntity basicDataEntity = basicDataService.findByMykeyAndFlowId(myKey, flowId);
					basicDataEntity.setStatus(PMPConstant.STATUS_0);
					basicDataService.updateById(basicDataEntity);
					String param = basicDataEntity.getParam();
					InvestCapitalEntity investCapitalEntity = JSON.parseObject(param, InvestCapitalEntity.class);
//						InvestCapitalEntity investCapitalEntity = investCapitalService.getById(flowId);//直接从缓存数据拿，做修改
					investCapitalEntity.setCheckStatus(PMPConstant.STATUS_0);
					investCapitalService.updateById(investCapitalEntity);
				}
			}
			//完成任务
			taskService.complete(task.getId(), map);
		}
	}


	/**
	 * 审核通过数据新增
	 *
	 * @param flowId
	 * @param oldMyKey
	 * @param newMyKey
	 */
	private void dataAdd(String flowId, String oldMyKey, String newMyKey) {
		BasicDataEntity basicDataEntity = basicDataService.findByMykeyAndFlowId(oldMyKey, flowId);
		String param = basicDataEntity.getParam();
		JSONObject jsonObject = JSONObject.parseObject(param);
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(newMyKey);

		String externalParameterId = deployFormMappingEntity.getExternalParameterId();
		//获取项目表单配置
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)) {
			throw new RuntimeException("项目表单配置参数不能为空");
		}
		basicLoadService.add(jsonObject.getJSONObject("param"), externalParameterEntity.getPlace(), flowId);
		//表格数据
		JSONObject data = jsonObject.getJSONObject("data");
		Set<String> keySet = data.keySet();
		for (String s : keySet) {
			JSONArray jsonArray = data.getJSONArray(s);
			for (int i = 0; i < jsonArray.size(); i++) {
				basicLoadService.add(jsonArray.getJSONObject(i), s, flowId);
			}
		}
//		String time = jsonObject.getJSONObject("param").getOrDefault("yjqysj", "").toString();
//		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		//存储数据信息关联表
		if (PMPConstant.TABLE_SJ.equals(oldMyKey)) {
			YYDataInfoEntity yyDataInfoEntity = new YYDataInfoEntity();
			yyDataInfoEntity.setFlowId(flowId);
			yyDataInfoEntity.setCreator(AuthUtil.getUser().getUserId());
			yyDataInfoEntity.setMyKey(newMyKey);
			yyDataInfoEntity.setStatus(PMPConstant.STATUS_0);
			yyDataInfoEntity.setCreateTime(LocalDateTime.now());
			/*if (StringUtil.isEmpty(time)) {
			} else {
				yyDataInfoEntity.setCreateTime(LocalDateTime.parse(time, df));
			}*/
			yyDataInfoService.save(yyDataInfoEntity);
		} else {
			YYDataInfoEntity yyDataInfoEntity = yyDataInfoService.getBusinessKey(flowId);
			yyDataInfoEntity.setStatus(PMPConstant.STATUS_0);
			yyDataInfoService.updateById(yyDataInfoEntity);
		}
		basicDataEntity.setStatus(PMPConstant.STATUS_0);//修改数据为完成
		basicDataService.updateById(basicDataEntity);
	}

	/**
	 * 获取流程部署流程的信息
	 *
	 * @param deploymentId
	 * @return
	 */
	private Deployment findDeploymentInfo(String deploymentId) {
		RepositoryService repositoryService = Activiti7Util.repositoryService;
		Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
		return deployment;
	}

	/**
	 * 获取部署流程的key值
	 *
	 * @param deploymentId
	 * @return
	 */
	private String findProcdefKey(String deploymentId) {
		RepositoryService repositoryService = Activiti7Util.repositoryService;
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
		return processDefinition.getKey();
	}

	/**
	 * 查询已办任务列表
	 *
	 * @return
	 */
	@Override
	public List<HistoricActivityInstance> findCompleteTask(String processId) {

		UserInfo user = AuthUtil.getUser();
		List<HistoricActivityInstance> list = Activiti7Util.historyService.createHistoricActivityInstanceQuery().processInstanceId(processId).list();
		return list;
	}

	@Override
	public Map<String, List<HistoryVO>> taskHistoryInfo(String processId) {
		List<HistoryVO> list = investCapitalService.taskHistoryInfo(processId);
		List<HistoryVO> historyVOS = new ArrayList<>();
		String formKey = "";
		for (HistoryVO hai : list) {
			if (hai.getActType().equals("startEvent") || hai.getActType().equals("userTask") || hai.getActType().equals("endEvent")) {
				HistoryVO historyVO = new HistoryVO();
				historyVO.setStartTime(hai.getStartTime());
				historyVO.setActivityName(hai.getActivityName());
				historyVO.setNodeForm(hai.getNodeForm());
				//如果是结束节点
				if ("endEvent".equals(hai.getActType())) {
					historyVO.setNodeForm(formKey);
				}
				formKey = hai.getNodeForm();
				if (ObjectUtil.isNotEmpty(hai.getEndTime())) {
					historyVO.setEndTime(hai.getEndTime());
				}
				setAssigneeAndSetColourMethod(hai, historyVO);
				historyVOS.add(historyVO);
			}
		}
		Map<String, List<HistoryVO>> map = new HashMap<>();
		map.put("historyTaskList", historyVOS);
		return map;
	}

	/**
	 * 查询当前用户发起的任务
	 *
	 * @return
	 */
	@Override
	public List<UserTaskVo> findTaskByUser() {
		UserInfo user = AuthUtil.getUser();
		List<UserTaskVo> list = basicDataService.listByUserId(user.getUserId());
		return list;
	}


	/**
	 * 设置受理人和历史信息颜色
	 *
	 * @param hai
	 * @param historyVO
	 * @return
	 */
	private void setAssigneeAndSetColourMethod(HistoryVO hai, HistoryVO historyVO) {
		if (hai.getActType().equals("userTask") && StringUtil.isBlank(hai.getAssignee())) {
			historyVO.setAssignee(findCandidate(hai.getProcessInstanceId()));
		} else if (hai.getActType().equals("userTask") && StringUtil.isNotBlank(hai.getAssignee())) {
			historyVO.setAssignee(findUserRealName(hai.getAssignee()));
		} else if (hai.getActType().equals("endEvent")) {
			historyVO.setColour(consentColor);
		}
		String taskId = hai.getTaskId();
		TbCompleteTaskStatusEntity statusServiceOne = completeTaskStatusService.getOne(new LambdaQueryWrapper<TbCompleteTaskStatusEntity>()
			.eq(TbCompleteTaskStatusEntity::getTaskId, taskId));
		if (ObjectUtil.isNotEmpty(statusServiceOne)) {
			if (consent.equals(statusServiceOne.getStatus())) {
				//蓝色
				historyVO.setColour(consentColor);
			} else if (notConsent.equals(statusServiceOne.getStatus())) {
				//红色
				historyVO.setColour(notConsentColor);
			} else if (reload.contains(statusServiceOne.getStatus())) {
				//蓝色
				historyVO.setColour(consentColor);
			}
			historyVO.setApprovalProposal(statusServiceOne.getApprovalProposal());
		} else {
			//如果为空证明还在审批中 蓝色
			historyVO.setColour(consentColor);
		}
	}


	/**
	 * 查询候选人
	 *
	 * @param processInstanceId
	 * @return
	 */
	private String findCandidate(String processInstanceId) {
		TaskService taskService = Activiti7Util.taskService;
		Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
		List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(task.getId());
		StringBuilder candidates = new StringBuilder();
		for (IdentityLink identityLink : identityLinksForTask) {
			if (StringUtil.isNotBlank(identityLink.getUserId())) {
				candidates.append(findUserRealName(identityLink.getUserId())).append(",");
			} else if (StringUtil.isNotBlank(identityLink.getGroupId())) {
				candidates.append(findUserRealName(identityLink.getGroupId())).append(",");
			}
		}
		return candidates.substring(0, candidates.length() - 1);
	}

	/**
	 * 查询用户组名称
	 *
	 * @param groupId
	 * @return
	 */
	private String findGroupName(String groupId) {
		UserGroupEntity userGroup = userGroupService.getOne(new LambdaQueryWrapper<UserGroupEntity>()
			.eq(UserGroupEntity::getId, groupId));
		return userGroup==null?"":userGroup.getGroupName();
	}

	/**
	 * 查询用户名称
	 *
	 * @param userId
	 */
	private String findUserRealName(String userId) {
		User user = userDubboApi.getUser(Long.valueOf(userId));
		if (ObjectUtil.isEmpty(user)){
			throw new ServiceException("查询用户为空");
		}
		return user.getRealName();
	}


	@Override
	public HashMap<String, ArrayList<TaskManageVo>> projectAudit() {
		UserInfo user = AuthUtil.getUser();
		HashMap<String, ArrayList<TaskManageVo>> taskMap = new HashMap<>();
		//只有刘萍萍可以催办
		if (!user.getUserId().toString().equals(PMPConstant.USER_ID_LPP)) {
			return taskMap;
		}
		ArrayList<String> taskList = new ArrayList<>();
		taskList.add(PMPConstant.TABLE_UPD);
		taskList.add(PMPConstant.TABLE_SJ_TQ_INFO);
		taskList.forEach(taskName -> {
			//查询所有未完成任务
			List<BasicDataEntity> list = basicDataService.listByMyKey(taskName);
			ArrayList<TaskManageVo> taskManageVos = new ArrayList<>();
			//实施人工天
			if (taskName.equals(PMPConstant.TABLE_SJ_TQ_INFO)) {
				list.forEach(x -> {
					TaskManageVo taskManageVo = new TaskManageVo();
					//表格id
					String flowId = x.getFlowId();
					String tableId = investCapitalService.getById(flowId).getFlowId();
					//根据flowId查询项目名称
					String pmpName = basicLoadService.getPmpValue(PMPConstant.KEY_XMMC, tableId);
					//根据flowId查询项目经理名称
					String managerName = basicLoadService.getPmpValue(PMPConstant.KEY_XMJL, tableId);
					String processId = x.getProcessId();
					Map<String, List<HistoryVO>> map = this.taskHistoryInfo(processId);
					taskManageVo.setManagerName(managerName);
					taskManageVo.setPmpName(pmpName);
					taskManageVo.setMyKey(taskName);
					taskManageVo.setProcessId(processId);
					taskManageVo.setFlowId(flowId);
					taskManageVo.setMap(map);
					boolean flag = urgeCheckService.getByMykeyAndProcessId(taskName, processId, PMPConstant.STATUS_1);
					taskManageVo.setStatus(flag ? 0 : 1);
					taskManageVos.add(taskManageVo);
				});
				taskMap.put(taskName, taskManageVos);
			}
			//商机数据修改
			if (taskName.equals(PMPConstant.TABLE_UPD)) {
				list.forEach(x -> {
					TaskManageVo taskManageVo = new TaskManageVo();
					//表格id
					String tableId = x.getFlowId();
					//根据flowId查询项目名称
					String pmpName = basicLoadService.getPmpValueByBus(PMPConstant.KEY_XMMC, tableId);
					//根据flowId查询项目经理名称
					String managerName = basicLoadService.getPmpValueByBus(PMPConstant.KEY_XMJL, tableId);
					String processId = x.getProcessId();
					Map<String, List<HistoryVO>> map = this.taskHistoryInfo(processId);
					taskManageVo.setManagerName(managerName);
					taskManageVo.setPmpName(pmpName);
					taskManageVo.setMyKey(taskName);
					taskManageVo.setProcessId(processId);
					taskManageVo.setFlowId(tableId);
					taskManageVo.setMap(map);
					boolean flag = urgeCheckService.getByMykeyAndProcessId(taskName, processId, PMPConstant.STATUS_1);
					taskManageVo.setStatus(flag ? 0 : 1);
					taskManageVos.add(taskManageVo);
				});
			}
			taskMap.put(taskName, taskManageVos);
		});

		return taskMap;
	}

	@Override
	public HashMap<String, Object> findToDoTaskCount(String UserId) {
		HashMap<String, Object> map = new HashMap<>();
//		List<YYTaskVo> sjAdd = this.findToDoTask(PMPConstant.TABLE_SJ,UserId);//商机新增任务
		ArrayList<String> list = new ArrayList<>();
		list.add(PMPConstant.TABLE_UPD);//商机修改任务
		list.add(PMPConstant.TABLE_SJ_TQ_INFO);//商机实施人工天任务
		list.add(PMPConstant.TABLE_RK_SS_INFO);//入库实施人工天任务
		list.add(PMPConstant.TABLE_RK_YW_INFO);//入库运维人工天任务
		list.forEach(x -> {
			//数量不多，不用多线程
			/*CompletableFuture<List<YYTaskVo>> listCompletableFuture = CompletableFuture.supplyAsync(() -> {

				List<YYTaskVo> toDoTask = this.findToDoTask(x, UserId);
				return toDoTask;
			}, Executors.newFixedThreadPool(10));
			try {
				map.put(x,listCompletableFuture.get().size());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}*/
			List<YYTaskVo> toDoTask = this.findToDoTask(x, UserId);
			map.put(x, toDoTask.size());
		});

		return map;
	}


	/**
	 * 一键催促-可以催促多个
	 *
	 * @param taskManageVos
	 * @return
	 */
	@Override
	public boolean urge(List<TaskManageVo> taskManageVos) {
		UserInfo user = AuthUtil.getUser();
		LinkedList<UrgeCheckEntity> urgeList = new LinkedList<>();
		taskManageVos.forEach(x -> {
			Integer status = x.getStatus();
			String myKey = x.getMyKey();
			String flowId = x.getFlowId();
			String processId = x.getProcessId();
			String pmpName = x.getPmpName();
			//是否存在审批任务
			boolean flag = urgeCheckService.getByMykeyAndProcessId(myKey, processId, PMPConstant.STATUS_1);
			//如果已催审的，则跳过不用再催
			if (status == PMPConstant.STATUS_0 || flag) {
				return;
			}
			Map<String, List<HistoryVO>> map = x.getMap();
			List<HistoryVO> list = map.get("historyTaskList");
			HistoryVO historyVO = list.get(list.size() - 1);
			UrgeCheckEntity urgeCheckEntity = new UrgeCheckEntity();
			urgeCheckEntity.setPmpName(pmpName);
			urgeCheckEntity.setInitiator(user.getRealName());//催审人
			urgeCheckEntity.setRecipient(historyVO.getAssignee());//审批人
			urgeCheckEntity.setFlowId(flowId);
			urgeCheckEntity.setProcessId(processId);
			urgeCheckEntity.setStatus(PMPConstant.STATUS_1);//默认为未看
			urgeCheckEntity.setCreateTime(LocalDateTime.now());
			urgeCheckEntity.setMyKey(myKey);
			urgeList.add(urgeCheckEntity);
		});
		return urgeCheckService.saveBatch(urgeList);
	}

	/**
	 * 获取当前用户的催办任务
	 *
	 * @return
	 */
	@Override
	public List<UrgeCheckEntity> getUrgeTask() {
		UserInfo user = AuthUtil.getUser();
		List<UrgeCheckEntity> list = urgeCheckService.listByRecipient(user.getRealName());
		return list;
	}

	@Override
	public boolean finishTask(Long id) {
		UserInfo user = AuthUtil.getUser();
		UrgeCheckEntity urgeCheckEntity = urgeCheckService.getById(id);
		urgeCheckEntity.setLookUser(user.getRealName());
		urgeCheckEntity.setStatus(PMPConstant.STATUS_0);
		return urgeCheckService.updateById(urgeCheckEntity);
	}

	/**
	 * 强制删除已部署流程定义
	 *
	 * @param id
	 * @return
	 */
	@Override
	public boolean deleteDeploy(String id) {
		RepositoryService repositoryService = ProcessEngines.getDefaultProcessEngine().getRepositoryService();
		repositoryService.deleteDeployment(id, true);
		return true;
	}
}
